package com.yotoodesign.dianba.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;

import com.yotoodesign.dianba.bean.Singer;
import com.yotoodesign.dianba.bean.Song;
import com.yotoodesign.dianba.bean.Tag;

/*
 * Top10歌曲服务
 */
public class Top10SongService extends Pager{
	private static Top10SongService songService ;
	
	public static Top10SongService getInstance(){
		if(songService==null){
			songService = new Top10SongService();
		}
		return songService;
	}
	
	/*
	 * 初始化数据
	 */
	public void prepare(String xmlFile){
		File file = new File(xmlFile);
		// 如果当前文件不存在，取当前应用内的文件
		boolean exists = file.exists();
		if (!exists) {
			Log.i(Constant.DIANBA,"not found ,read from self app.");
			String[] ps = xmlFile.split("/");
			if(ps.length>0){
				xmlFile = "/"+ps[ps.length-1];
			}
		}
		Log.i(Constant.DIANBA,"file name="+xmlFile);
		List<Song> result = new ArrayList<Song>();
		Top10SongService saxSongService=new Top10SongService();
		InputStream istream = null;
		if(exists){
			try {
				istream = new FileInputStream(xmlFile);
			} catch (FileNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} 
		}else{
			Log.i(Constant.DIANBA,"not found ,read from self app.");
			istream=saxSongService.getClass().getResourceAsStream(xmlFile);
		}
		
		try {
			result = saxSongService.getService(istream);
			this.init(result, 0);
		} catch (Throwable e) {
			Log.i(Constant.DIANBA,">>>>>>>>>>>>>>get "+xmlFile+" error!["+e.getMessage()+"]");
		}
	}
	
	// 要解析的XML文件以流的方式传进来
	public List<Song> getService(InputStream istream) throws Throwable {
		SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
		SAXParser saxParser = saxParserFactory.newSAXParser();
		SongHandler SongHandler = new SongHandler();
		saxParser.parse(istream, SongHandler);
		// 当解析过程中遇到符合XML语法规定的语句时就会调用第2个参数所规定的方法
		return SongHandler.getSongs();
	}
	
	private final class SongHandler extends DefaultHandler {
		private List<Song> songs;
		private Song song;
		private String TAG;// 存放当前所遍历的元素节点
		
		@Override
		public void characters(char[] ch, int start, int length)
				throws SAXException {
			super.characters(ch, start, length);
			if (TAG != null) {
				String data = new String(ch, start, length);
				if (song != null) {
					if ("id".equals(TAG)) {
						song.setId(data);
					} else if ("name".equals(TAG)) {
						song.setName(data);
					}else if ("desc".equals(TAG)) {
						song.setDesc(data);
					} else if ("image_url".equals(TAG)) {
						song.setImageUrl(data);
					} else if ("pinyin".equals(TAG)) {
						song.setPinyin(data);
					} else if ("language_type".equals(TAG)) {
						song.setLanguageType(data);
					} else if ("favorites_count".equals(TAG)) {
						song.setFavoritesCount(Integer.parseInt(data));
					} else if ("is_two_singer".equals(TAG)) {
						song.setTwoSinger(data.equals("1")?true:false);
					}else if ("tags".equals(TAG)) {
						String[] ts = data.split(",");
						for(int i = 0;i<ts.length;i++){
							song.addTag(new Tag(ts[i]));
						}
					} else if ("lrc".equals(TAG)) {
						song.setLrc(data);
					} else if ("timestamp".equals(TAG)) {
						song.setTimestamp(data);
					} else if ("create_date".equals(TAG)) {
						song.setCreateDate(data);
					} else if ("update_date".equals(TAG)) {
						song.setUpdateDate(data);
					} else if ("singer".equals(TAG)) {
						String singerId = data;
						Singer singer = new Singer();
						singer.setId(singerId);
						song.setSinger(singer);
					}
					
				}
			}
		}
		
		@Override
		public void startDocument() throws SAXException {
			super.startDocument();
			songs = new ArrayList<Song>();
		}

		@Override
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {
			super.startElement(uri, localName, qName, attributes);
			// localName:不含命名空间前缀的标签名
			// qName:含有命名空间前缀的标签名
			// attributes:接收属性值
			if ("song".equals(localName)) {
				song = new Song();
			}
			
			TAG = localName;
		}

		public List<Song> getSongs() {
			return songs;
		}		

		@Override
		public void endDocument() throws SAXException {
			super.endDocument();
		}

		@Override
		public void endElement(String uri, String localName, String qName)
				throws SAXException {
			super.endElement(uri, localName, qName);
			if ("song".equals(localName)) {
				songs.add(song);
				song = null;
			}
			TAG = null;
		}


		
	}
}
